package com.robcity.platform.util;



import com.robcity.platform.common.BusinessException;
import com.robcity.platform.common.Result;
import com.robcity.platform.enums.RespEnum;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * restTemplate 公共调用服务
 */
@Service
public class RestTemplateUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(RestTemplateUtil.class);

    @Resource
    private RestTemplate restTemplate;

    /**
     * POST 请求
     *
     * @param url 请求url
     * @param data 入参
     * @return T
     */
    public Object sendPost(String url, Object data) {
        if (StringUtils.isBlank(url)) {
            throw new BusinessException(RespEnum.NOT_FOUND);
        }

        Result<?> response = restTemplate.postForObject(url, data, Result.class);
        if (Objects.nonNull(response)) {
            // code != 2003 时，请求失败
            if (!Objects.equals(RespEnum.OPERATE_SUCCESS.getCode(), response.getCode())) {
                throw new RuntimeException(response.getMessage());
            }
            return response.getData();
        }
        return null;
    }

}
